package com.example.servlet;

import com.example.dao.CustomerDao;
import com.example.dao.GuitarDao;
import com.example.dao.PurchaseRecordDao;
import com.example.entity.Customer;
import com.example.entity.PurchaseRecord;
import com.google.gson.Gson;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet("/customer")
public class CustomerServlet extends HttpServlet {
    private CustomerDao customerDao = new CustomerDao();
    private GuitarDao guitarDao = new GuitarDao();
    private PurchaseRecordDao purchaseRecordDao = new PurchaseRecordDao();
    private Gson gson = new Gson();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("list".equals(action)) {
            List<Customer> customers = customerDao.findAll();
            request.setAttribute("customers", customers);

            request.setAttribute("customerCount", customers.size());
            request.setAttribute("guitarCount", guitarDao.findAll().size());

            List<PurchaseRecord> allRecords = purchaseRecordDao.findAll();
            request.setAttribute("purchaseCount", allRecords.size());

            List<PurchaseRecord> recentRecords = allRecords.stream()
                    .sorted((r1, r2) -> r2.getPurchaseTime().compareTo(r1.getPurchaseTime()))
                    .limit(5)
                    .collect(Collectors.toList());
            request.setAttribute("recentRecords", recentRecords);

            request.getRequestDispatcher("index.jsp").forward(request, response);
        } else if ("get".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            Customer customer = customerDao.findById(id);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(gson.toJson(customer));
        } else if ("delete".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            Customer currentUser = (Customer) request.getSession().getAttribute("customer");
            if (currentUser != null && currentUser.getId() == id) {
                response.setContentType("application/json");
                response.getWriter().write("{\"success\":false,\"message\":\"不能删除当前登录用户\"}");
                return;
            }
            customerDao.delete(id);
            response.sendRedirect("customer?action=list");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");

        if ("add".equals(action)) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String gender = request.getParameter("gender");
            String phone = request.getParameter("phone");

            if (customerDao.findByUsername(username) != null) {
                response.setContentType("application/json");
                response.getWriter().write("{\"success\":false,\"message\":\"用户名已存在\"}");
                return;
            }

            Customer customer = new Customer(username, password, gender, phone);
            customerDao.add(customer);
            response.sendRedirect("customer?action=list");
        } else if ("edit".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String gender = request.getParameter("gender");
            String phone = request.getParameter("phone");

            Customer existingCustomer = customerDao.findById(id);

            if (!existingCustomer.getUsername().equals(username)) {
                Customer customerWithNewUsername = customerDao.findByUsername(username);
                if (customerWithNewUsername != null) {
                    response.setContentType("application/json");
                    response.getWriter().write("{\"success\":false,\"message\":\"用户名已存在\"}");
                    return;
                }
                existingCustomer.setUsername(username);
            }

            if (password != null && !password.trim().isEmpty()) {
                existingCustomer.setPassword(password);
            }
            existingCustomer.setGender(gender);
            existingCustomer.setPhone(phone);

            customerDao.update(existingCustomer);

            Customer currentUser = (Customer) request.getSession().getAttribute("customer");
            if (currentUser != null && currentUser.getId() == id) {
                request.getSession().setAttribute("customer", existingCustomer);
            }

            response.sendRedirect("customer?action=list");
        }
    }
} 